package com.qian.service.ddj.serviceImpl;

import com.qian.api.ddj.model.CheckCode;
import com.qian.api.ddj.service.ICheckCodeService;
import com.qian.service.ddj.dao.CheckCodeRepository;
import com.qian.service.ddj.entity.SysCheckCode;
import com.yaowk.service.common.BaseRepository;
import com.yaowk.service.common.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

/**
 * 验证码server实现类
 *@author 屈子威
 * @date 2018年1月10日11:12:53
 */
@Service
public class CheckCodeServiceImpl extends BaseServiceImpl<CheckCode,SysCheckCode,Long>implements ICheckCodeService {
   @Autowired
   private CheckCodeRepository dao;

    @Override
    @Transactional
    public boolean checkCode(CheckCode checkCode) {
        SysCheckCode entity = dao.findOne(Example.of(model2Entity(checkCode)));
        if (isNotEmpty(entity)){
            dao.delete(entity.getId());
            return true;
        }else{
            return false;
        }
    }

    @Override
    @Transactional
    public CheckCode save(CheckCode model) {
        if (model.isNew()){
            model = entity2model(dao.save(model2Entity(model)));
        }else{
            SysCheckCode entity = dao.findOne(model.getId());
            if (isNotEmpty(model.getSessionId())){
                entity.setSessionId(model.getSessionId());
            }

            if (isNotEmpty(model.getCode())){
                entity.setCode(model.getCode());
            }
            model = entity2model(dao.save(entity));
        }
        return model;
    }

    @Override
    protected BaseRepository getDao() {
        return dao;
    }

    @Override
    protected SysCheckCode model2Entity(CheckCode model) {
        SysCheckCode entity = null;
        if (isNotEmpty(model)){
            entity  = new SysCheckCode();
            entity.setCode(model.getCode());
            entity.setSessionId(model.getSessionId());
            entity.setId(model.getId());
        }
        return entity;
    }

    @Override
    protected CheckCode entity2model(SysCheckCode entity) {
        CheckCode model = null;
        if (isNotEmpty(entity)){
            model = new CheckCode();
            model.setCode(entity.getCode());
            model.setSessionId(entity.getSessionId());
            model.setId(entity.getId());
        }
        return model;
    }


    protected SysCheckCode updateParams(CheckCode model) {
        return null;
    }
}
